'use client';

import { useState, useEffect, use } from 'react';
import { Box, Container, Typography, Paper, Alert, Snackbar, CircularProgress, Divider } from '@mui/material';
import { useRouter } from 'next/navigation';
import { examApi } from '@/api/exams';

interface ExamResult {
  score: number;
  passingScore: number;
  totalScore: number;
  answers: {
    questionId: number;
    question: {
      id: number;
      type: string;
      content: string;
      options: string[];
      answer: string;
      explanation: string;
      score: number;
    };
    answer: string;
    isCorrect: boolean;
    score: number;
  }[];
}

export default function ExamResultPage({ params }: { params: { id: string } }) {
  const resolvedParams = use(params);
  const [result, setResult] = useState<ExamResult | null>(null);
  const [loading, setLoading] = useState(true);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();

  useEffect(() => {
    const fetchResult = async () => {
      try {
        const data = await examApi.getExamResult(Number(resolvedParams.id));
        setResult(data);
      } catch (error) {
        setSnackbar({ open: true, message: '获取考试结果失败', severity: 'error' });
        router.push('/student-exams');
      } finally {
        setLoading(false);
      }
    };

    fetchResult();
  }, [resolvedParams.id, router]);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <CircularProgress size={60} />
      </div>
    );
  }

  if (!result) {
    return null;
  }

  const isPassed = result.score >= result.passingScore;

  const getAnswerDisplay = (type: string, answer: string, options: string[]) => {
    switch (type) {
      case 'CHOICE':
        const optionIndex = answer.charCodeAt(0) - 65;
        return `${answer}. ${options[optionIndex]}`;
      case 'TRUE_FALSE':
        return answer === 'true' ? '正确' : '错误';
      default:
        return answer;
    }
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" gutterBottom>
          考试结果
        </Typography>

        <Paper sx={{ p: 3, mb: 4, bgcolor: isPassed ? '#e8f5e9' : '#ffebee' }}>
          <Typography variant="h5" gutterBottom color={isPassed ? 'success.main' : 'error.main'}>
            {isPassed ? '恭喜你通过考试！' : '很遗憾，未能通过考试。'}
          </Typography>
          <Typography variant="h6" gutterBottom>
            得分：{result.score} / {result.totalScore}
          </Typography>
          <Typography variant="subtitle1">
            及格分：{result.passingScore}
          </Typography>
        </Paper>

        <Typography variant="h5" gutterBottom sx={{ mt: 4 }}>
          答题详情
        </Typography>

        {result.answers.map((answer, index) => (
          <Paper key={answer.questionId} sx={{ p: 3, mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              第 {index + 1} 题（{answer.question.score} 分）
              <Box component="span" sx={{ float: 'right', color: answer.isCorrect ? 'success.main' : 'error.main' }}>
                得分：{answer.score}
              </Box>
            </Typography>

            <Typography variant="body1" paragraph>
              {answer.question.content}
            </Typography>

            {answer.question.type === 'CHOICE' && (
              <Box sx={{ mb: 2 }}>
                {answer.question.options.map((option, optionIndex) => (
                  <Typography
                    key={optionIndex}
                    variant="body2"
                    sx={{
                      color: String.fromCharCode(65 + optionIndex) === answer.question.answer ? 'success.main' : 
                             String.fromCharCode(65 + optionIndex) === answer.answer ? 'error.main' : 'text.primary'
                    }}
                  >
                    {String.fromCharCode(65 + optionIndex)}. {option}
                  </Typography>
                ))}
              </Box>
            )}

            <Box sx={{ mt: 2 }}>
              <Typography variant="body2" color="text.secondary">
                你的答案：{getAnswerDisplay(answer.question.type, answer.answer, answer.question.options)}
              </Typography>
              <Typography variant="body2" color="success.main">
                正确答案：{getAnswerDisplay(answer.question.type, answer.question.answer, answer.question.options)}
              </Typography>
            </Box>

            {answer.question.explanation && (
              <Box sx={{ mt: 2 }}>
                <Divider sx={{ my: 1 }} />
                <Typography variant="body2" color="text.secondary">
                  解析：{answer.question.explanation}
                </Typography>
              </Box>
            )}
          </Paper>
        ))}
      </Box>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
}